#include <stdio.h>
#include "main.h"
#include "lcd.h"
#include "w5100.h"
#include "HttpServer.h"
#include "Keyboard.h"
#include "menu.h"
#include "UARTS.h"
#include "UpDown.h"
#include "UdpControl.h"
/* delete this.
int putchar(int ch)
{
  tcp.WriteBuf((uint8_t *)&ch, 1);
  return ch;
}
*/
uint8_t eth_rx_buf[256];

int main()
{
  menu.Refresh();
  __delay_cycles(QUARZ_FREQ / 2);
  udp1.DPORT(53001);
  
  usart0.setMyAdr(dev_control.getSerialAdres());
  
  __enable_interrupt();
  
  up.SetAtt(up.getAtt(), false);
  up.SetOnOff(up.getOnOff(), false);
  up.SetFrq(up.getFrq(), false);
  
  down.SetTAGC(down.getTAGC(), false);
  down.SetAgcPwr(down.getAgcPwr(), false);
  down.SetFrq(down.getFrq(), false);
  down.SetOnOff(down.getOnOff(), false);
  down.SetAgc(down.getAgc(), false);
  down.SetAttIn(down.getAttIn(), false);
  down.SetAttOut(down.getAttOut(), false);
  
  for (;;)
  {
    switch (tcp.SR())
    {
      case SOCK_ESTABLISHED:
        if (tcp.RX_RSR())
        {
          size_t len = tcp.Read_TCP(eth_rx_buf, sizeof(eth_rx_buf));
          SendHttpResponce(eth_rx_buf, len/*, TODO IP*/);
          tcp.Send();
          tcp.Disconnect();
        }
        break;
      case SOCK_CLOSED:
        tcp.Open();
        break;
      case SOCK_CLOSE_WAIT:
        tcp.Close();
        break;
      case SOCK_INIT:
        tcp.Listen();
        break;
    }
    
    if (keys.KeyPressed()) menu.Do(keys.ReadKey());
    
    if (usart0.isCommandReceived())
    {
      usart0.DoCmd();
    }
    
    if (usart1.getFlag())
    {
      down.ReadP();
      usart1.setFlag(false);
    }
    
    if (udp1.IR() & Sn_IR_RECV)
    {
      UDP_HEADER header;
      const uint16_t tmp_rx_rsr = udp1.RX_RSR();
      if (tmp_rx_rsr > MAX_UDP_RX_PACKET_SIZE)
      {
        udp1.Read_SKIP();
      }
      else
      {
        udp1.Read_UDP((uint8_t *)(&header), eth_rx_buf, tmp_rx_rsr);
        udp1.DIPR(header.d_ip);
        udp_control.DoCmd();
      }
      if (!udp1.RX_RSR()) udp1.IR(Sn_IR_RECV);
    }
  }
}
